package com.xingfly.event;

import com.xingfly.common.utils.JsonUtil;
import com.xingfly.event.shared.model.DomainEvent;
import lombok.Data;

import javax.persistence.*;
import java.time.LocalDateTime;

/**
 * 事件表
 * Created by SuperS on 2019/11/15.
 *
 * @author SuperS
 */
@Data
@Entity
@Table(name = "t_event")
public class Event {
    @Id
    private String id;

    @Lob
    @Column(columnDefinition = "text")
    private String json;

    private Boolean deleted;

    private String className;

    private LocalDateTime createTime;

    public static Event create(DomainEvent event) {
        Event e = new Event();
        e.setId(event.getEventId());
        e.setJson(JsonUtil.toJson(event));
        e.setClassName(event.getClass().getName());
        e.setCreateTime(event.getEventCreateTime());
        e.setDeleted(Boolean.FALSE);
        return e;
    }

    public static DomainEvent toDomainEvent(Event event) {
        DomainEvent e = null;
        try {
            e = (DomainEvent) JsonUtil.fromJson(event.getJson(), Class.forName(event.getClassName()));
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return e;
    }
}
